What is the purpose of the volatile keyword in Java?
What is the purpose of the volatile keyword in Java?
557
18-Jul-2024
Ravi Vishwakarma
18-Jul-2024Here's a detailed explanation of its purpose and usage:
Visibility: When a variable is declared as
volatile, it guarantees that any thread that reads the field will see the most recently written value. This is because the value of avolatilevariable is always read from and written to the main memory, bypassing the local cache.Atomicity: The
volatilekeyword ensures visibility but does not guarantee atomicity. Operations onvolatilevariables are not atomic, which means operations like incrementing a variable (count++) are not thread-safe withvolatilealone. If you need atomicity, you should usesynchronizedblocks or classes from thejava.util.concurrent.atomicpackage (e.g.,AtomicInteger).Instruction Reordering: The Java Memory Model allows the JVM to reorder instructions for performance optimization. However,
volatileprevents certain types of reordering, ensuring a happens-before relationship between the write and read of thevolatilevariable. This means that changes made by one thread before writing to avolatilethe variable is visible to other threads that subsequently read thatvolatilevariable.Example -
When to Use
volatileUse
volatilewhen you need to ensure visibility of changes to variables across threads, but only if:count++), which require atomicity.